<!DOCTYPE HTML>
<html lang="zh-CN">


<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta name="keywords" content="关于闭包那点事, Java 架构 Go Redis Mysql Kafka 算法 数据结构">
    <meta name="baidu-site-verification" content="fmlEuI34ir">
    <meta name="google-site-verification" content="yCy2azpds5XSuGZvis6OuA-XIGF5GuGpYRAaGfD6o48">
    <meta name="360-site-verification" content="b7c11a830ef90fd1464ad6206bb7b6e7">
    <meta name="description" content="


以前写 Java 的时候，听到前端同学谈论闭包，觉得甚是新奇，后面自己写了一小段时间 JS，虽只学到皮毛，也大概了解到闭包的概念，现在工作常用语言是 Go，很多优雅的代码中总是有闭包的身影，看来不了解个透是不可能的了，本文让我来科普(">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>关于闭包那点事 | 秦怀的博客</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <style type="text/css">
        
    </style>

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
    <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
    <script>
        var _hmt = _hmt || [];
        (function () {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?ce84511d3df71640a9378a69f6293044";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>

    
        <script>
            (function(){
                var bp = document.createElement('script');
                var curProtocol = window.location.protocol.split(':')[0];
                if (curProtocol === 'https') {
                    bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
                }
                else {
                    bp.src = 'http://push.zhanzhang.baidu.com/push.js';
                }
                var s = document.getElementsByTagName("script")[0];
                s.parentNode.insertBefore(bp, s);
            })();
        </script>
    

    <script>
        (function(){
        var src = "https://jspassport.ssl.qhimg.com/11.0.1.js?d182b3f28525f2db83acfaaf6e696dba";
        document.write('<script src="' + src + '" id="sozz"><\/script>');
        })();
    </script>

<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>

<body>

    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">秦怀的博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>友情链接</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/contact" class="waves-effect waves-light">
            
            <i class="fa fa-comments"></i>
            
            <span>留言板</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">秦怀的博客</div>
        <div class="logo-desc">
            
            喜欢代码 | 喜欢捣鼓 | 喜欢听音乐
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        <li>
            <a href="/contact" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-comments"></i>
                
                留言板
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/godweiyang/hexo-matery-modified" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/godweiyang/hexo-matery-modified" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/27.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        关于闭包那点事
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 20px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                        <a href="/tags/博客/" target="_blank">
                            <span class="chip bg-color">博客</span>
                        </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                        <a href="/categories/随笔/" class="post-category" target="_blank">
                            随笔
                        </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-01-14
                </div>

                <div class="post-author info-break-policy">
                    <i class="fa fa-user-o fa-fw"></i>作者:&nbsp;&nbsp;
                    
                    秦怀
                    
                </div>

                
                
                <div class="info-break-policy">
                    <i class="fa fa-file-word-o fa-fw"></i>文章字数:&nbsp;&nbsp;
                    6.3k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="fa fa-clock-o fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    25 分
                </div>
                
                

                
                <div id="busuanzi_container_page_pv" class="info-break-policy">
                    <i class="fa fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                    <span id="busuanzi_value_page_pv"></span>
                </div>
                
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <meta name="referrer" content="no-referrer">


<p>以前写 Java 的时候，听到前端同学谈论闭包，觉得甚是新奇，后面自己写了一小段时间 JS，虽只学到皮毛，也大概了解到闭包的概念，现在工作常用语言是 Go，很多优雅的代码中总是有闭包的身影，看来不了解个透是不可能的了，本文让我来科普(按照自己水平随便瞎扯)一下：</p>
<h1 id="1、什么是闭包？"><a href="#1、什么是闭包？" class="headerlink" title="1、什么是闭包？"></a>1、什么是闭包？</h1><p>在真正讲述闭包之前，我们先铺垫一点知识点：</p>
<ul>
<li><p>函数式编程</p>
</li>
<li><p>函数作用域</p>
</li>
<li><p>作用域的继承关系</p>
<h2 id="1-1-前提知识铺垫"><a href="#1-1-前提知识铺垫" class="headerlink" title="1.1 前提知识铺垫"></a>1.1 前提知识铺垫</h2></li>
</ul>
<h3 id="1-2-1-函数式编程"><a href="#1-2-1-函数式编程" class="headerlink" title="1.2.1 函数式编程"></a>1.2.1 函数式编程</h3><p>函数式编程是一种编程范式，看待问题的一种方式，每一个函数都是为了用小函数组织成为更大的函数，函数的参数也是函数，函数返回的也是函数。我们常见的编程范式有：</p>
<ul>
<li>命令式编程：<ul>
<li>主要思想为：关注计算机执行的步骤，也就是一步一步告诉计算机先做什么再做什么。</li>
<li>先把解决问题步骤规范化，抽象为某种算法，然后编写具体的算法去实现，一般只要支持过程化编程范式的语言，我们都可以称为过程化编程语言，比如 BASIC，C 等。</li>
</ul>
</li>
<li>声明式编程：<ul>
<li>主要思想为：告诉计算机应该做什么，但是不指定具体要怎么做，比如 SQL，网页编程的 HTML，CSS。</li>
</ul>
</li>
<li>函数式编程：<ul>
<li>只关注做什么而不关注怎么做，有一丝丝声明式编程的影子，但是更加侧重于”函数是第一位“的原则，也就是函数可以出现在任何地方，参数、变量、返回值等等。</li>
</ul>
</li>
</ul>
<p>函数式编程可以认为是面向对象编程的对立面，一般只有一些编程语言会强调一种特定的编程方式，大多数的语言都是多范式语言，可以支持多种不同的编程方式，比如 JavaScript ，Go 等。</p>
<p>函数式编程是一种思维方式，将电脑运算视为函数的计算，是一种写代码的方法论，<strong>其实我应该聊函数式编程，然后再聊到闭包，因为闭包本身就是函数式编程里面的一个特点之一。</strong></p>
<blockquote>
<p>在函数式编程中，函数是<a href="https://zh.wikipedia.org/wiki/头等对象" target="_blank" rel="noopener">头等对象</a>，意思是说一个函数，既可以作为其它函数的输入参数值，也可以从函数中返回值，被修改或者被分配给一个变量。(维基百科)</p>
</blockquote>
<p>一般纯函数编程语言是不允许直接使用程序状态以及可变对象的，函数式编程本身就是要避免使用 <strong>共享状态</strong>，<strong>可变状态</strong>，尽可能避免产生 <strong>副作用</strong>。</p>
<p>函数式编程一般具有以下特点：</p>
<ol>
<li><p>函数是第一等公民：函数的地位放在第一位，可以作为参数，可以赋值，可以传递，可以当做返回值。</p>
</li>
<li><p>没有副作用：函数要保持纯粹独立，不能修改外部变量的值，不修改外部状态。</p>
</li>
<li><p>引用透明：函数运行不依赖外部变量或者状态，相同的输入参数，任何情况，所得到的返回值都应该是一样的。</p>
</li>
</ol>
<h3 id="1-2-2-函数作用域"><a href="#1-2-2-函数作用域" class="headerlink" title="1.2.2 函数作用域"></a>1.2.2 函数作用域</h3><p><strong>作用域</strong>（scope），程序设计概念，通常来说，一段程序代码中所用到的名字并不总是有效/可用的，而限定这个名字的可用性的代码范围就是这个名字的<em>作用域</em>。</p>
<p>通俗易懂的说，函数作用域是指函数可以起作用的范围。函数有点像盒子，一层套一层，作用域我们可以理解为是个封闭的盒子，也就是函数的局部变量，只能在盒子内部使用，成为独立作用域。</p>
<p><img src="https://gitee.com/Damaer/pic/raw/master/image-20221112163921104.png" alt="image-20221112163921104"></p>
<p>函数内的局部变量，出了函数就跳出了作用域，找不到该变量。（里层函数可以使用外层函数的局部变量，因为外层函数的作用域包括了里层函数），比如下面的 <code>innerTmep</code> 出了函数作用域就找不到该变量，但是 <code>outerTemp</code> 在内层函数里面还是可以使用。</p>
<p><img src="https://gitee.com/Damaer/pic/raw/master/image-20221112164640101.png" alt="image-20221112164640101"></p>
<p>不管是任何语言，基本存在一定的内存回收机制，也就是回收用不到的内存空间，回收的机制一般和上面说的函数的作用域是相关的，局部变量出了其作用域，就有可能被回收，如果还被引用着，那么就不会被回收。</p>
<h3 id="1-2-3-作用域的继承关系"><a href="#1-2-3-作用域的继承关系" class="headerlink" title="1.2.3 作用域的继承关系"></a>1.2.3 作用域的继承关系</h3><p>所谓作用域继承，就是前面说的小盒子可以继承外层大盒子的作用域，在小盒子可以直接取出大盒子的东西，但是大盒子不能取出小盒子的东西，除非发生了逃逸（逃逸可以理解为小盒子的东西给出了引用，大盒子拿到就可以使用）。一般而言，变量的作用域有以下两种：</p>
<ul>
<li><p>全局作用域：作用于任何地方</p>
</li>
<li><p>局部作用域：一般是代码块，函数、包内，<strong>函数内部</strong>声明/定义的变量叫<strong>局部变量</strong>，<strong>作用域仅限于函数内部</strong></p>
</li>
</ul>
<h2 id="1-2-闭包的定义"><a href="#1-2-闭包的定义" class="headerlink" title="1.2 闭包的定义"></a>1.2 闭包的定义</h2><p>“多数情况下我们并不是先理解后定义，而是先定义后理解“，先下定义，<strong>读不懂没关系</strong>：</p>
<blockquote>
<p>闭包（closure）是<strong>一个函数以及其捆绑的周边环境状态（lexical environment，词法环境）的引用的组合</strong>。 换而言之，闭包让开发者可以从内部函数访问外部函数的作用域。 闭包会随着函数的创建而被同时创建。</p>
</blockquote>
<p>一句话表述：<br>$$<br>闭包 = 函数 + 引用环境<br>$$</p>
<p>以上定义找不到 Go语言 这几个字眼，聪明的同学肯定知道，闭包是和语言无关的，不是 JavaScript 特有的，也不是 Go 特有的，而是<strong>函数式编程语言</strong>的特有的，是的，你没有看错，<strong>任何支持函数式编程的语言都支持闭包，Go 和 JavaScript 就是其中之二， 目前 Java 目前版本也是支持闭包的</strong>，但是有些人可能认为不是完美的闭包，详细情况文中讨论。</p>
<h2 id="1-3-闭包的写法"><a href="#1-3-闭包的写法" class="headerlink" title="1.3 闭包的写法"></a>1.3 闭包的写法</h2><h3 id="1-3-1-初看闭包"><a href="#1-3-1-初看闭包" class="headerlink" title="1.3.1 初看闭包"></a>1.3.1 初看闭包</h3><p>下面是一段闭包的代码：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    sumFunc <span class="token operator">:=</span> <span class="token function">lazySum</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"等待一会"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">sumFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">lazySum</span><span class="token punctuation">(</span>arr <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"先获取函数，不求结果"</span><span class="token punctuation">)</span>
    <span class="token keyword">var</span> sum <span class="token operator">=</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"求结果..."</span><span class="token punctuation">)</span>
        result <span class="token operator">:=</span> <span class="token number">0</span>
        <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> arr <span class="token punctuation">{</span>
            result <span class="token operator">=</span> result <span class="token operator">+</span> v
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> result
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> sum
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出的结果：</p>
<pre class="line-numbers language-shell"><code class="language-shell">先获取函数，不求结果
等待一会
求结果...
结果： 15<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以看出，里面的 <code>sum()</code> 方法可以引用外部函数 <code>lazySum()</code> 的参数以及局部变量，在<code>lazySum()</code>返回函数 <code>sum()</code> 的时候，相关的参数和变量都保存在返回的函数中，可以之后再进行调用。</p>
<p>上面的函数或许还可以更进一步，体现出捆绑函数和其周围的状态，我们加上一个次数 <code>count</code>：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    sumFunc <span class="token operator">:=</span> <span class="token function">lazySum</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"等待一会"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">sumFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">sumFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">sumFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">lazySum</span><span class="token punctuation">(</span>arr <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"先获取函数，不求结果"</span><span class="token punctuation">)</span>
    count <span class="token operator">:=</span> <span class="token number">0</span>
    <span class="token keyword">var</span> sum <span class="token operator">=</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
        count<span class="token operator">++</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"第"</span><span class="token punctuation">,</span> count<span class="token punctuation">,</span> <span class="token string">"次求结果..."</span><span class="token punctuation">)</span>
        result <span class="token operator">:=</span> <span class="token number">0</span>
        <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> arr <span class="token punctuation">{</span>
            result <span class="token operator">=</span> result <span class="token operator">+</span> v
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> result
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> sum
<span class="token punctuation">}</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上面代码输出什么呢？次数 <code>count</code> 会不会发生变化，<code>count</code>明显是外层函数的局部变量，但是在内存函数引用（捆绑），内层函数被暴露出去了，执行结果如下：</p>
<pre class="line-numbers language-shell"><code class="language-shell">先获取函数，不求结果
等待一会
第 1 次求结果...
结果： 15
第 2 次求结果...
结果： 15
第 3 次求结果...
结果： 15<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>结果是 <code>count</code> 其实每次都会变化，这种情况总结一下：</p>
<ul>
<li>函数体内嵌套了另外一个函数，并且返回值是一个函数。</li>
<li>内层函数被暴露出去，被<strong>外层函数以外</strong>的地方引用着，形成了闭包。</li>
</ul>
<p>此时有人可能有疑问了，前面是<code>lazySum（）</code>被创建了 1 次，执行了 3 次，但是如果是 3 次执行都是不同的创建，会是怎么样呢？实验一下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    sumFunc <span class="token operator">:=</span> <span class="token function">lazySum</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"等待一会"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">sumFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

    sumFunc1 <span class="token operator">:=</span> <span class="token function">lazySum</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"等待一会"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">sumFunc1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

    sumFunc2 <span class="token operator">:=</span> <span class="token function">lazySum</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"等待一会"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">sumFunc2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">lazySum</span><span class="token punctuation">(</span>arr <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"先获取函数，不求结果"</span><span class="token punctuation">)</span>
    count <span class="token operator">:=</span> <span class="token number">0</span>
    <span class="token keyword">var</span> sum <span class="token operator">=</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
        count<span class="token operator">++</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"第"</span><span class="token punctuation">,</span> count<span class="token punctuation">,</span> <span class="token string">"次求结果..."</span><span class="token punctuation">)</span>
        result <span class="token operator">:=</span> <span class="token number">0</span>
        <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> arr <span class="token punctuation">{</span>
            result <span class="token operator">=</span> result <span class="token operator">+</span> v
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> result
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> sum
<span class="token punctuation">}</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>执行的结果如下，每次执行都是第 1 次：</p>
<pre class="line-numbers language-shell"><code class="language-shell">先获取函数，不求结果
等待一会
第 1 次求结果...
结果： 15
先获取函数，不求结果
等待一会
第 1 次求结果...
结果： 15
先获取函数，不求结果
等待一会
第 1 次求结果...
结果： 15<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>从以上的执行结果可以看出：</p>
<p><strong>闭包被创建的时候，引用的外部变量<code>count</code>就已经被创建了 1 份，也就是各自调用是没有关系的</strong>。</p>
<p>继续抛出一个问题，<strong>如果一个函数返回了两个函数，这是一个闭包还是两个闭包呢？</strong>下面我们实践一下：</p>
<p>一次返回两个函数，一个用于计算加和的结果，一个计算乘积：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    sumFunc<span class="token punctuation">,</span> productSFunc <span class="token operator">:=</span> <span class="token function">lazyCalculate</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"等待一会"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">sumFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">productSFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">lazyCalculate</span><span class="token punctuation">(</span>arr <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"先获取函数，不求结果"</span><span class="token punctuation">)</span>
    count <span class="token operator">:=</span> <span class="token number">0</span>
    <span class="token keyword">var</span> sum <span class="token operator">=</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
        count<span class="token operator">++</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"第"</span><span class="token punctuation">,</span> count<span class="token punctuation">,</span> <span class="token string">"次求加和..."</span><span class="token punctuation">)</span>
        result <span class="token operator">:=</span> <span class="token number">0</span>
        <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> arr <span class="token punctuation">{</span>
            result <span class="token operator">=</span> result <span class="token operator">+</span> v
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> result
    <span class="token punctuation">}</span>

    <span class="token keyword">var</span> product <span class="token operator">=</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
        count<span class="token operator">++</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"第"</span><span class="token punctuation">,</span> count<span class="token punctuation">,</span> <span class="token string">"次求乘积..."</span><span class="token punctuation">)</span>
        result <span class="token operator">:=</span> <span class="token number">0</span>
        <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> arr <span class="token punctuation">{</span>
            result <span class="token operator">=</span> result <span class="token operator">*</span> v
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> result
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> sum<span class="token punctuation">,</span> product
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>运行结果如下：</p>
<pre class="line-numbers language-shell"><code class="language-shell">先获取函数，不求结果
等待一会
第 1 次求加和...
结果： 15
第 2 次求乘积...
结果： 0<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>从上面结果可以看出，闭包是函数返回函数的时候，不管多少个返回值(函数)，都是一次闭包，如果返回的函数有使用外部函数变量，则会绑定到一起，相互影响：</p>
<p><img src="https://gitee.com/Damaer/pic/raw/master/image-20221119001944927.png" alt="image-20221119001944927"></p>
<p>闭包绑定了周围的状态，我理解此时的函数就拥有了状态，让函数具有了对象所有的能力，函数具有了状态。</p>
<h3 id="1-3-2-闭包中的指针和值"><a href="#1-3-2-闭包中的指针和值" class="headerlink" title="1.3.2 闭包中的指针和值"></a>1.3.2 闭包中的指针和值</h3><p>上面的例子，我们闭包中用到的都是数值，如果我们传递指针，会是怎么样的呢？</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">import</span> <span class="token string">"fmt"</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    i <span class="token operator">:=</span> <span class="token number">0</span>
    testFunc <span class="token operator">:=</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>i<span class="token punctuation">)</span>
    <span class="token function">testFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"outer i = %d\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">test</span><span class="token punctuation">(</span>i <span class="token operator">*</span><span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token operator">*</span>i <span class="token operator">=</span> <span class="token operator">*</span>i <span class="token operator">+</span> <span class="token number">1</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"test inner i = %d\n"</span><span class="token punctuation">,</span> <span class="token operator">*</span>i<span class="token punctuation">)</span>
    <span class="token keyword">return</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token operator">*</span>i <span class="token operator">=</span> <span class="token operator">*</span>i <span class="token operator">+</span> <span class="token number">1</span>
        fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"func inner i = %d\n"</span><span class="token punctuation">,</span> <span class="token operator">*</span>i<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>运行结果如下：</p>
<pre class="line-numbers language-shell"><code class="language-shell">test inner i = 1
func inner i = 2
outer i = 2<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>可以看出如果是指针的话，闭包里面修改了指针对应的地址的值，也会影响闭包外面的值。这个其实很容易理解，Go 里面没有引用传递，只有值传递，那我们传递指针的时候，也是值传递，这里的值是指针的数值（可以理解为地址值）。</p>
<p>当我们函数的参数是指针的时候，参数会拷贝一份这个指针地址，当做参数进行传递，因为本质还是地址，所以内部修改的时候，仍然可以对外部产生影响。</p>
<p> 闭包里面的数据其实地址也是一样的，下面的实验可以证明：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    i <span class="token operator">:=</span> <span class="token number">0</span>
    testFunc <span class="token operator">:=</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>i<span class="token punctuation">)</span>
    <span class="token function">testFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"outer i address %v\n"</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>i<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">test</span><span class="token punctuation">(</span>i <span class="token operator">*</span><span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token operator">*</span>i <span class="token operator">=</span> <span class="token operator">*</span>i <span class="token operator">+</span> <span class="token number">1</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"test inner i address %v\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span>
    <span class="token keyword">return</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token operator">*</span>i <span class="token operator">=</span> <span class="token operator">*</span>i <span class="token operator">+</span> <span class="token number">1</span>
        fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"func inner i address %v\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出如下, 因此可以推断出，闭包如果引用外部环境的指针数据，只是会拷贝一份指针地址数据，而不是拷贝一份真正的数据(==先留个问题：拷贝的时机是什么时候呢==)：</p>
<pre class="line-numbers language-go"><code class="language-go">test inner i address <span class="token number">0xc0003fab98</span>
<span class="token keyword">func</span> inner i address <span class="token number">0xc0003fab98</span>
outer i address <span class="token number">0xc0003fab98</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h3 id="1-3-2-闭包延迟化"><a href="#1-3-2-闭包延迟化" class="headerlink" title="1.3.2 闭包延迟化"></a>1.3.2 闭包延迟化</h3><p>上面的例子仿佛都在告诉我们，闭包创建的时候，数据就已经拷贝了，但是真的是这样么？</p>
<p>下面是继续前面的实验：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    i <span class="token operator">:=</span> <span class="token number">0</span>
    testFunc <span class="token operator">:=</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>i<span class="token punctuation">)</span>
    i <span class="token operator">=</span> i <span class="token operator">+</span> <span class="token number">100</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"outer i before testFunc  %d\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span>
    <span class="token function">testFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"outer i after testFunc %d\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">test</span><span class="token punctuation">(</span>i <span class="token operator">*</span><span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token operator">*</span>i <span class="token operator">=</span> <span class="token operator">*</span>i <span class="token operator">+</span> <span class="token number">1</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"test inner i = %d\n"</span><span class="token punctuation">,</span> <span class="token operator">*</span>i<span class="token punctuation">)</span>
    <span class="token keyword">return</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token operator">*</span>i <span class="token operator">=</span> <span class="token operator">*</span>i <span class="token operator">+</span> <span class="token number">1</span>
        fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"func inner i = %d\n"</span><span class="token punctuation">,</span> <span class="token operator">*</span>i<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>我们在创建闭包之后，把数据改了，之后执行闭包，答案肯定是真实影响闭包的执行，因为它们都是指针，都是指向同一份数据：</p>
<pre class="line-numbers language-shell"><code class="language-shell">test inner i = 1
outer i before testFunc  101
func inner i = 102
outer i after testFunc 102<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>假设我们换个写法，让闭包外部环境中的变量在声明闭包函数的之后，进行修改：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    sumFunc <span class="token operator">:=</span> <span class="token function">lazySum</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"等待一会"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">sumFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">lazySum</span><span class="token punctuation">(</span>arr <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"先获取函数，不求结果"</span><span class="token punctuation">)</span>
    count <span class="token operator">:=</span> <span class="token number">0</span>
    <span class="token keyword">var</span> sum <span class="token operator">=</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"第"</span><span class="token punctuation">,</span> count<span class="token punctuation">,</span> <span class="token string">"次求结果..."</span><span class="token punctuation">)</span>
        result <span class="token operator">:=</span> <span class="token number">0</span>
        <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> arr <span class="token punctuation">{</span>
            result <span class="token operator">=</span> result <span class="token operator">+</span> v
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> result
    <span class="token punctuation">}</span>
    count <span class="token operator">=</span> count <span class="token operator">+</span> <span class="token number">100</span>
    <span class="token keyword">return</span> sum
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>实际执行结果，<code>count</code> 会是修改后的值：</p>
<pre class="line-numbers language-shell"><code class="language-shell">等待一会
第 100 次求结果...
结果： 15<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>这也证明了，实际上闭包并不会在声明<code>var sum = func() int {...}</code>这句话之后，就将外部环境的 <code>count</code>绑定到闭包中，而是在函数返回闭包函数的时候，才绑定的，这就是<strong>延迟绑定</strong>。</p>
<p>如果还没看明白没关系，我们再来一个例子：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    funcs <span class="token operator">:=</span> <span class="token function">testFunc</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> funcs <span class="token punctuation">{</span>
        <span class="token function">v</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">testFunc</span><span class="token punctuation">(</span>x <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> funcs <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    values <span class="token operator">:=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">}</span>
    <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> val <span class="token operator">:=</span> <span class="token keyword">range</span> values <span class="token punctuation">{</span>
        funcs <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>funcs<span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"testFunc val = %d\n"</span><span class="token punctuation">,</span> x<span class="token operator">+</span>val<span class="token punctuation">)</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> funcs
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上面的例子，我们闭包返回的是函数数组，本意我们想入每一个 <code>val</code> 都不一样，但是实际上 <code>val</code>都是一个值，==也就是执行到<code>return funcs</code> 的时候（或者真正执行闭包函数的时候）才绑定的 <code>val</code>值==（关于这一点，后面还有个Demo可以证明），此时 <code>val</code>的值是最后一个 <code>3</code>,最终输出结果都是 <code>103</code>:</p>
<pre class="line-numbers language-shell"><code class="language-shell">testFunc val = 103
testFunc val = 103
testFunc val = 103<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>以上两个例子，都是闭包延迟绑定的问题导致，这也可以说是 feature，到这里可能不少同学还是对闭包绑定外部变量的时机有疑惑，到底是返回闭包函数的时候绑定的呢？还是真正执行闭包函数的时候才绑定的呢？</p>
<p>下面的例子可以有效的解答：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"fmt"</span>
    <span class="token string">"time"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    sumFunc <span class="token operator">:=</span> <span class="token function">lazySum</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"等待一会"</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">sumFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    time<span class="token punctuation">.</span><span class="token function">Sleep</span><span class="token punctuation">(</span>time<span class="token punctuation">.</span><span class="token function">Duration</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"结果："</span><span class="token punctuation">,</span> <span class="token function">sumFunc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">lazySum</span><span class="token punctuation">(</span>arr <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"先获取函数，不求结果"</span><span class="token punctuation">)</span>
    count <span class="token operator">:=</span> <span class="token number">0</span>
    <span class="token keyword">var</span> sum <span class="token operator">=</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
        count<span class="token operator">++</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"第"</span><span class="token punctuation">,</span> count<span class="token punctuation">,</span> <span class="token string">"次求结果..."</span><span class="token punctuation">)</span>
        result <span class="token operator">:=</span> <span class="token number">0</span>
        <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> arr <span class="token punctuation">{</span>
            result <span class="token operator">=</span> result <span class="token operator">+</span> v
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> result
    <span class="token punctuation">}</span>
    <span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        time<span class="token punctuation">.</span><span class="token function">Sleep</span><span class="token punctuation">(</span>time<span class="token punctuation">.</span><span class="token function">Duration</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">)</span>
        count <span class="token operator">=</span> count <span class="token operator">+</span> <span class="token number">100</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"go func 修改后的变量 count："</span><span class="token punctuation">,</span> count<span class="token punctuation">)</span>
    <span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> sum
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>输出结果如下：</p>
<pre class="line-numbers language-shell"><code class="language-shell">先获取函数，不求结果
等待一会
第 1 次求结果...
结果： 15
go func 修改后的变量 count： 101
第 102 次求结果...
结果： 15<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>第二次执行闭包函数的时候，明显 <code>count</code>被里面的 <code>go func()</code>修改了，也就是调用的时候，才真正的获取最新的外部环境，但是在声明的时候，就会把环境预留保存下来。</p>
<p>其实本质上，<strong>Go Routine的匿名函数的延迟绑定就是闭包的延迟绑定</strong>，上面的例子中，<code>go func(){}</code>获取到的就是最新的值，而不是原始值<code>0</code>。</p>
<p>总结一下上面的验证点：</p>
<ul>
<li>闭包每次返回都是一个新的实例，每个实例都有一份自己的环境。</li>
<li>同一个实例多次执行，会使用相同的环境。</li>
<li>闭包如果逃逸的是指针，会相互影响，因为绑定的是指针，相同指针的内容修改会相互影响。</li>
<li>闭包并不是在声明时绑定的值，声明后只是预留了外部环境（逃逸分析），真正执行闭包函数时，会获取最新的外部环境的值（也称为延迟绑定）。</li>
<li>Go Routine的匿名函数的延迟绑定本质上就是闭包的延迟绑定。</li>
</ul>
<h1 id="2、闭包的好处与坏处？"><a href="#2、闭包的好处与坏处？" class="headerlink" title="2、闭包的好处与坏处？"></a>2、闭包的好处与坏处？</h1><h2 id="2-1-好处"><a href="#2-1-好处" class="headerlink" title="2.1 好处"></a>2.1 好处</h2><p>纯函数没有状态，而闭包则是让函数轻松拥有了状态。但是凡事都有两面性，一旦拥有状态，多次调用，可能会出现不一样的结果，就像是前面测试的 case 中一样。那么问题来了：</p>
<p>Q：<strong>如果不支持闭包的话，我们想要函数拥有状态，需要怎么做呢？</strong></p>
<p>A： 需要使用全局变量，让所有函数共享同一份变量。</p>
<p>但是我们都知道全局变量有以下的一些特点（在不同的场景，优点会变成缺点）：</p>
<ul>
<li>常驻于内存之中，只要程序不停会一直在内存中。</li>
<li>污染全局，大家都可以访问，共享的同时不知道谁会改这个变量。</li>
</ul>
<p>闭包可以一定程度优化这个问题：</p>
<ul>
<li>不需要使用全局变量，外部函数局部变量在闭包的时候会创建一份，生命周期与函数生命周期一致，闭包函数不再被引用的时候，就可以回收了。</li>
<li>闭包暴露的局部变量，外界无法直接访问，只能通过函数操作，可以避免滥用。</li>
</ul>
<p>除了以上的好处，像在 JavaScript 中，没有原生支持私有方法，可以靠闭包来模拟私有方法，因为闭包都有自己的词法环境。</p>
<h2 id="2-2-坏处"><a href="#2-2-坏处" class="headerlink" title="2.2 坏处"></a>2.2 坏处</h2><p>函数拥有状态，如果处理不当，会导致闭包中的变量被误改，但这是编码者应该考虑的问题，是预期中的场景。</p>
<p>闭包中如果随意创建，引用被持有，则无法销毁，同时闭包内的局部变量也无法销毁，过度使用闭包会占有更多的内存，导致性能下降。一般而言，能共享一份闭包（共享闭包局部变量数据），不需要多次创建闭包函数，是比较优雅的方式。</p>
<h1 id="3、闭包怎么实现的？"><a href="#3、闭包怎么实现的？" class="headerlink" title="3、闭包怎么实现的？"></a>3、闭包怎么实现的？</h1><p>从上面的实验中，我们可以知道，闭包实际上就是外部环境的逃逸，跟随着闭包函数一起暴露出去。</p>
<p>我们用以下的程序进行分析：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">import</span> <span class="token string">"fmt"</span>

<span class="token keyword">func</span> <span class="token function">testFunc</span><span class="token punctuation">(</span>i <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    i <span class="token operator">=</span> i <span class="token operator">*</span> <span class="token number">2</span>
    testFunc <span class="token operator">:=</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
        i<span class="token operator">++</span>
        <span class="token keyword">return</span> i
    <span class="token punctuation">}</span>
    i <span class="token operator">=</span> i <span class="token operator">*</span> <span class="token number">2</span>
    <span class="token keyword">return</span> testFunc
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    test <span class="token operator">:=</span> <span class="token function">testFunc</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>执行结果如下：</p>
<pre class="line-numbers language-shell"><code class="language-shell">5<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>先看看逃逸分析，用下面的命令行可以查看：</p>
<pre class="line-numbers language-shell"><code class="language-shell"> go build --gcflags=-m main.go<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://gitee.com/Damaer/pic/raw/master/image-20221120223253318.png" alt="image-20221120223253318"></p>
<p>可以看到 变量 <code>i</code>被移到堆中，也就是本来是局部变量，但是发生逃逸之后，从栈里面放到堆里面，同样的 <code>test()</code>函数由于是闭包函数，也逃逸到堆上。</p>
<p>下面我们用命令行来看看汇编代码：</p>
<pre class="line-numbers language-shell"><code class="language-shell">go tool compile -N -l -S main.go<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>生成代码比较长，我截取一部分：</p>
<pre class="line-numbers language-shell"><code class="language-shell">"".testFunc STEXT size=218 args=0x8 locals=0x38 funcid=0x0 align=0x0
        0x0000 00000 (main.go:5)        TEXT    "".testFunc(SB), ABIInternal, $56-8
        0x0000 00000 (main.go:5)        CMPQ    SP, 16(R14)
        0x0004 00004 (main.go:5)        PCDATA  $0, $-2
        0x0004 00004 (main.go:5)        JLS     198
        0x000a 00010 (main.go:5)        PCDATA  $0, $-1
        0x000a 00010 (main.go:5)        SUBQ    $56, SP
        0x000e 00014 (main.go:5)        MOVQ    BP, 48(SP)
        0x0013 00019 (main.go:5)        LEAQ    48(SP), BP
        0x0018 00024 (main.go:5)        FUNCDATA        $0, gclocals·69c1753bd5f81501d95132d08af04464(SB)
        0x0018 00024 (main.go:5)        FUNCDATA        $1, gclocals·d571c0f6cf0af59df28f76498f639cf2(SB)
        0x0018 00024 (main.go:5)        FUNCDATA        $5, "".testFunc.arginfo1(SB)
        0x0018 00024 (main.go:5)        MOVQ    AX, "".i+64(SP)
        0x001d 00029 (main.go:5)        MOVQ    $0, "".~r0+16(SP)
        0x0026 00038 (main.go:5)        LEAQ    type.int(SB), AX
        0x002d 00045 (main.go:5)        PCDATA  $1, $0
        0x002d 00045 (main.go:5)        CALL    runtime.newobject(SB)
        0x0032 00050 (main.go:5)        MOVQ    AX, "".&i+40(SP)
        0x0037 00055 (main.go:5)        MOVQ    "".i+64(SP), CX
        0x003c 00060 (main.go:5)        MOVQ    CX, (AX)
        0x003f 00063 (main.go:6)        MOVQ    "".&i+40(SP), CX
        0x0044 00068 (main.go:6)        MOVQ    "".&i+40(SP), DX
        0x0049 00073 (main.go:6)        MOVQ    (DX), DX
        0x004c 00076 (main.go:6)        SHLQ    $1, DX
        0x004f 00079 (main.go:6)        MOVQ    DX, (CX)
        0x0052 00082 (main.go:7)        LEAQ    type.noalg.struct { F uintptr; "".i *int }(SB), AX
        0x0059 00089 (main.go:7)        PCDATA  $1, $1
        0x0059 00089 (main.go:7)        CALL    runtime.newobject(SB)
        0x005e 00094 (main.go:7)        MOVQ    AX, ""..autotmp_3+32(SP)
        0x0063 00099 (main.go:7)        LEAQ    "".testFunc.func1(SB), CX
        0x006a 00106 (main.go:7)        MOVQ    CX, (AX)
        0x006d 00109 (main.go:7)        MOVQ    ""..autotmp_3+32(SP), CX
        0x0072 00114 (main.go:7)        TESTB   AL, (CX)
        0x0074 00116 (main.go:7)        MOVQ    "".&i+40(SP), DX
        0x0079 00121 (main.go:7)        LEAQ    8(CX), DI
        0x007d 00125 (main.go:7)        PCDATA  $0, $-2
        0x007d 00125 (main.go:7)        CMPL    runtime.writeBarrier(SB), $0
        0x0084 00132 (main.go:7)        JEQ     136
        0x0086 00134 (main.go:7)        JMP     142
        0x0088 00136 (main.go:7)        MOVQ    DX, 8(CX)
        0x008c 00140 (main.go:7)        JMP     149
        0x008e 00142 (main.go:7)        CALL    runtime.gcWriteBarrierDX(SB)
        0x0093 00147 (main.go:7)        JMP     149
        0x0095 00149 (main.go:7)        PCDATA  $0, $-1
        0x0095 00149 (main.go:7)        MOVQ    ""..autotmp_3+32(SP), CX
        0x009a 00154 (main.go:7)        MOVQ    CX, "".testFunc+24(SP)
        0x009f 00159 (main.go:11)       MOVQ    "".&i+40(SP), CX
        0x00a4 00164 (main.go:11)       MOVQ    "".&i+40(SP), DX
        0x00a9 00169 (main.go:11)       MOVQ    (DX), DX
        0x00ac 00172 (main.go:11)       SHLQ    $1, DX
        0x00af 00175 (main.go:11)       MOVQ    DX, (CX)
        0x00b2 00178 (main.go:12)       MOVQ    "".testFunc+24(SP), AX
        0x00b7 00183 (main.go:12)       MOVQ    AX, "".~r0+16(SP)
        0x00bc 00188 (main.go:12)       MOVQ    48(SP), BP
        0x00c1 00193 (main.go:12)       ADDQ    $56, SP
        0x00c5 00197 (main.go:12)       RET
        0x00c6 00198 (main.go:12)       NOP
        0x00c6 00198 (main.go:5)        PCDATA  $1, $-1
        0x00c6 00198 (main.go:5)        PCDATA  $0, $-2
        0x00c6 00198 (main.go:5)        MOVQ    AX, 8(SP)
        0x00cb 00203 (main.go:5)        CALL    runtime.morestack_noctxt(SB)
        0x00d0 00208 (main.go:5)        MOVQ    8(SP), AX
        0x00d5 00213 (main.go:5)        PCDATA  $0, $-1
        0x00d5 00213 (main.go:5)        JMP     0
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以看到闭包函数实际上底层也是用结构体<code>new</code>创建出来的：</p>
<p><img src="https://gitee.com/Damaer/pic/raw/master/image-20221120224413412.png" alt="image-20221120224413412"></p>
<p>使用的就是堆上面的<code>i</code>：</p>
<p><img src="https://gitee.com/Damaer/pic/raw/master/image-20221120225532865.png" alt="image-20221120225532865"></p>
<p>也就是返回函数的时候，实际上返回结构体，结构体里面记录了函数的引用环境。</p>
<h1 id="4、浅聊一下"><a href="#4、浅聊一下" class="headerlink" title="4、浅聊一下"></a>4、浅聊一下</h1><h2 id="4-1-Java-支不支持闭包？"><a href="#4-1-Java-支不支持闭包？" class="headerlink" title="4.1 Java 支不支持闭包？"></a>4.1 Java 支不支持闭包？</h2><p>网上有很多种看法，实际上 Java 虽然暂时不支持返回函数作为返参，但是Java 本质上还是实现了闭包的概念的，所使用的的方式是内部类的形式，因为是内部类，所以相当于自带了一个引用环境，算是一种不完整的闭包。</p>
<p>目前有一定限制，比如是 <code>final</code>声明的，或者是明确定义的值，才可以进行传递：</p>
<p>Stack Overflow上有相关答案：<a href="https://stackoverflow.com/questions/5443510/closure-in-java-7" target="_blank" rel="noopener">https://stackoverflow.com/questions/5443510/closure-in-java-7</a></p>
<p><img src="https://gitee.com/Damaer/pic/raw/master/image-20221120233223203.png" alt="image-20221120233223203"></p>
<h2 id="4-2-函数式编程的前景怎么样？"><a href="#4-2-函数式编程的前景怎么样？" class="headerlink" title="4.2 函数式编程的前景怎么样？"></a>4.2 函数式编程的前景怎么样？</h2><p>下面是Wiki的内容：</p>
<blockquote>
<p>函数式编程长期以来在学术界流行，但几乎没有工业应用。造成这种局面的主因是函数式编程常被认为严重耗费CPU和存储器资源<a href="https://zh.wikipedia.org/wiki/函数式编程#cite_note-18" target="_blank" rel="noopener">[18]</a> ，这是由于在早期实现函数式编程语言时并没有考虑过效率问题，而且面向函数式编程特性，如保证<a href="https://zh.wikipedia.org/w/index.php?title=参照透明性&action=edit&redlink=1" target="_blank" rel="noopener">参照透明性</a>等，要求独特的数据结构和算法。<a href="https://zh.wikipedia.org/wiki/函数式编程#cite_note-programmingScala-19" target="_blank" rel="noopener">[19]</a></p>
<p>然而，最近几种函数式编程语言已经在商业或工业系统中使用<a href="https://zh.wikipedia.org/wiki/函数式编程#cite_note-20" target="_blank" rel="noopener">[20]</a>，例如：</p>
<ul>
<li><a href="https://zh.wikipedia.org/wiki/Erlang" target="_blank" rel="noopener">Erlang</a>，它由瑞典公司<a href="https://zh.wikipedia.org/wiki/爱立信" target="_blank" rel="noopener">爱立信</a>在20世纪80年代后期开发，最初用于实现容错电信系统。此后，它已在<a href="https://zh.wikipedia.org/wiki/北电网络" target="_blank" rel="noopener">Nortel</a>、<a href="https://zh.wikipedia.org/wiki/Facebook" target="_blank" rel="noopener">Facebook</a>、<a href="https://zh.wikipedia.org/wiki/法国电力公司" target="_blank" rel="noopener">Électricité de France</a>和<a href="https://zh.wikipedia.org/wiki/WhatsApp" target="_blank" rel="noopener">WhatsApp</a>等公司作为流行语言创建一系列应用程序。<a href="https://zh.wikipedia.org/wiki/函数式编程#cite_note-21" target="_blank" rel="noopener">[21]</a><a href="https://zh.wikipedia.org/wiki/函数式编程#cite_note-whatsapp.blog.2012-22" target="_blank" rel="noopener">[22]</a></li>
<li><a href="https://zh.wikipedia.org/wiki/Scheme" target="_blank" rel="noopener">Scheme</a>，它被用作早期<a href="https://zh.wikipedia.org/wiki/苹果公司" target="_blank" rel="noopener">Apple</a> <a href="https://zh.wikipedia.org/wiki/Macintosh" target="_blank" rel="noopener">Macintosh</a>计算机上的几个应用程序的基础，并且最近已应用于诸如训练模拟软件和望远镜控制等方向。</li>
<li><a href="https://zh.wikipedia.org/wiki/OCaml" target="_blank" rel="noopener">OCaml</a>，它于20世纪90年代中期推出，已经在金融分析，驱动程序验证，工业机器人编程和嵌入式软件静态分析等领域得到了商业应用。</li>
<li><a href="https://zh.wikipedia.org/wiki/Haskell" target="_blank" rel="noopener">Haskell</a>，它虽然最初是作为一种研究语言，也已被一系列公司应用于航空航天系统，硬件设计和网络编程等领域。</li>
</ul>
<p>其他在工业中使用的函数式编程语言包括多范型的<a href="https://zh.wikipedia.org/wiki/Scala" target="_blank" rel="noopener">Scala</a><a href="https://zh.wikipedia.org/wiki/函数式编程#cite_note-23" target="_blank" rel="noopener">[23]</a>、<a href="https://zh.wikipedia.org/wiki/F＃" target="_blank" rel="noopener">F#</a>，还有<a href="https://zh.wikipedia.org/wiki/Wolfram语言" target="_blank" rel="noopener">Wolfram语言</a>、<a href="https://zh.wikipedia.org/wiki/Common_Lisp" target="_blank" rel="noopener">Common Lisp</a>、<a href="https://zh.wikipedia.org/wiki/Standard_ML" target="_blank" rel="noopener">Standard ML</a>和<a href="https://zh.wikipedia.org/wiki/Clojure" target="_blank" rel="noopener">Clojure</a>等。</p>
</blockquote>
<p>从我个人的看法，不看好纯函数编程，但是函数式编程的思想，我相信以后几乎每门高级编程需要都会具备，特别期待 Java 拥抱函数式编程。从我自己了解的语言看，像 Go，JavaScript 中的函数式编程的特性，都让开发者深爱不已（当然，如果写出了bug，就是深恶痛疾）。</p>
<p>最近突然火了一波的原因，也是因为世界不停的发展，内存也越来越大，这个因素的限制几乎要解放了。</p>
<p>我相信，世界就是绚丽多彩的，要是一种事物统治世界，绝无可能，更多的是百家争鸣，编程语言或者编程范式也一样，后续可能有集大成者，最终最终历史会筛选出最终符合人类社会发展的。</p>

            </div>
            <hr />

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">写作不易，客官能否打赏一杯奶茶？</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            

    <div class="reprint" id="reprint-statement">
        <p class="reprint-tip">
            <i class="fa fa-exclamation-triangle"></i>&nbsp;&nbsp;
            <span>转载规则</span>
        </p>
        
            <div class="center-align">
                <a rel="license" href="https://creativecommons.org/licenses/by/4.0/deed.zh">
                    <img alt=""
                         style="border-width:0"
                         src="https://i.creativecommons.org/l/by/4.0/88x31.png"/>
                </a>
            </div>
            <br/>
            <span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text"
                  property="dct:title" rel="dct:type">
                    《关于闭包那点事》
                </span> 由
            <a xmlns:cc="http://creativecommons.org/ns#" href="/2020/01/14/bi-bao-na-dian-shi/" property="cc:attributionName"
               rel="cc:attributionURL">
                秦怀
            </a> 采用
            <a rel="license" href="https://creativecommons.org/licenses/by/4.0/deed.zh">
                知识共享署名 4.0 国际许可协议
            </a>进行许可。
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>


        </div>
    </div>

    
    <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: '查教程获取',
        clientSecret: '查教程获取',
        repo: 'godweiyang.github.io',
        owner: 'godweiyang',
        admin: "godweiyang",
        id: '2020/01/14/bi-bao-na-dian-shi/',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    
    <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments input[type=text],
    #vcomments input[type=email],
    #vcomments input[type=url],
    #vcomments textarea {
        box-sizing: border-box;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #42b983;
        font-weight: 500;
        text-decoration: underline;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div id="vcomments" class="card-content"></div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<!-- <script src="//unpkg.com/valine@latest/dist/Valine.min.js"></script> -->

<script>
    new Valine({
        el: '#vcomments',
        appId: '查教程获取',
        appKey: '查教程获取',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'false' === 'true',
        avatar: 'wavatar',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: '如果你没有GitHub账号，还可以在这里评论啦！'
    });
</script>

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-dot-circle-o"></i>&nbsp;本篇
            </div>
            <div class="card">
                <a href="/2020/01/14/bi-bao-na-dian-shi/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/27.jpg" class="responsive-img" alt="关于闭包那点事">
                        
                        <span class="card-title">关于闭包那点事</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            


以前写 Java 的时候，听到前端同学谈论闭包，觉得甚是新奇，后面自己写了一小段时间 JS，虽只学到皮毛，也大概了解到闭包的概念，现在工作常用语言是 Go，很多优雅的代码中总是有闭包的身影，看来不了解个透是不可能的了，本文让我来科普(
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2020-01-14
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/随笔/" class="post-category" target="_blank">
                                    随笔
                                </a>
                            
                            
                        </span>
                    </div>
                </div>

                
                <div class="card-action article-tags">
                    
                    <a href="/tags/博客/" target="_blank">
                        <span class="chip bg-color">博客</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                本篇&nbsp;<i class="fa fa-dot-circle-o"></i>
            </div>
            <div class="card">
                <a href="/2020/01/14/bi-bao-na-dian-shi/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/27.jpg" class="responsive-img" alt="关于闭包那点事">
                        
                        <span class="card-title">关于闭包那点事</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            


以前写 Java 的时候，听到前端同学谈论闭包，觉得甚是新奇，后面自己写了一小段时间 JS，虽只学到皮毛，也大概了解到闭包的概念，现在工作常用语言是 Go，很多优雅的代码中总是有闭包的身影，看来不了解个透是不可能的了，本文让我来科普(
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2020-01-14
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/随笔/" class="post-category" target="_blank">
                                    随笔
                                </a>
                            
                            
                        </span>
                    </div>
                </div>

                
                <div class="card-action article-tags">
                    
                    <a href="/tags/博客/" target="_blank">
                        <span class="chip bg-color">博客</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 秦怀的博客<br />'
            + '作者: 秦怀<br />'
            + '链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () { bodyElement.removeChild(newdiv); }, 200);
    });
</script>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h1, h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\(', '\)']]}
    });
</script>

<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>
<!-- 代码语言 -->
<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>
<!-- 代码块复制 -->
<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>
<script type="text/javascript" src="/libs/codeBlock/clipboard.min.js"></script>
<!-- 代码块收缩 -->
<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script> 
<!-- 代码块折行 -->
<style type="text/css">code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }</style>


    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            &copy; 2017-2020 WeiYang. 版权所有

            
            &nbsp;<i class="fa fa-area-chart"></i>&nbsp;站点总字数:&nbsp;
            <span class="white-color">6.3k</span>
            

            <br>
            <span id="sitetime"></span>

            
            
            <br>
            
            <span id="busuanzi_container_site_pv" style='display:none'>
                <i class="fa fa-heart-o"></i>
                本站总访问量 <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
            <span id="busuanzi_container_site_uv" style='display:none'>
                人次,&nbsp;访客数 <span id="busuanzi_value_site_uv" class="white-color"></span> 人.
            </span>
            
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/godweiyang" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fa fa-github"></i>
    </a>



    <a href="mailto:godweiyang@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fa fa-envelope-open"></i>
    </a>



    <a href="https://zhihu.com/people/godweiyang" class="tooltipped" target="_blank" data-tooltip="访问我的知乎" data-position="top" data-delay="50">
        <i class="fa fa-inverse">知</i>
    </a>



    <a href="http://wpa.qq.com/msgrd?v=3&uin=792321264&site=qq&menu=yes" class="tooltipped" target="_blank" data-tooltip="访问我的知乎" data-position="top" data-delay="50">
        <i class="fa fa-qq"></i>
    </a>



    <a href="https://weibo.com/godweiyang" class="tooltipped" target="_blank" data-tooltip="关注我的微博" data-position="top" data-delay="50">
        <i class="fa fa-weibo"></i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fa fa-rss"></i>
    </a>
</div>
    </div>
</footer>

<div class="progress-bar"></div>

<!-- 不蒜子计数初始值纠正 -->
<script>
    $(document).ready(function () {

        var int = setInterval(fixCount, 50);
        var pvcountOffset = 80000;
        var uvcountOffset = 20000;

        function fixCount() {
            if (document.getElementById("busuanzi_container_site_pv").style.display != "none") {
                $("#busuanzi_value_site_pv").html(parseInt($("#busuanzi_value_site_pv").html()) + pvcountOffset);
                clearInterval(int);
            }
            if ($("#busuanzi_container_site_pv").css("display") != "none") {
                $("#busuanzi_value_site_uv").html(parseInt($("#busuanzi_value_site_uv").html()) + uvcountOffset); // 加上初始数据 
                clearInterval(int);
            }
        }
    });
</script>

<script language=javascript>
    function siteTime() {
        window.setTimeout("siteTime()", 1000);
        var seconds = 1000;
        var minutes = seconds * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var years = days * 365;
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth() + 1;
        var todayDate = today.getDate();
        var todayHour = today.getHours();
        var todayMinute = today.getMinutes();
        var todaySecond = today.getSeconds();
        /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
        year - 作为date对象的年份，为4位年份值
        month - 0-11之间的整数，做为date对象的月份
        day - 1-31之间的整数，做为date对象的天数
        hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
        minutes - 0-59之间的整数，做为date对象的分钟数
        seconds - 0-59之间的整数，做为date对象的秒数
        microseconds - 0-999之间的整数，做为date对象的毫秒数 */
        var t1 = Date.UTC(2017, 09, 11, 00, 00, 00); //北京时间2018-2-13 00:00:00
        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
        var diff = t2 - t1;
        var diffYears = Math.floor(diff / years);
        var diffDays = Math.floor((diff / days) - diffYears * 365);
        var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
        var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) / minutes);
        var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours - diffMinutes * minutes) / seconds);
        document.getElementById("sitetime").innerHTML = "本站已运行 " + diffYears + " 年 " + diffDays + " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
    }/*因为建站时间还没有一年，就将之注释掉了。需要的可以取消*/
    siteTime();
</script>

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <script type="text/javascript"> var OriginTitile = document.title, st; document.addEventListener("visibilitychange", function () { document.hidden ? (document.title = "Σ(っ °Д °;)っ喔哟，崩溃啦！", clearTimeout(st)) : (document.title = "φ(゜▽゜*)♪咦，又好了！", st = setTimeout(function () { document.title = OriginTitile }, 3e3)) })
    </script>

    <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id=查教程获取"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', '查教程获取');
</script>



    
    <script src="/libs/others/clicklove.js"></script>
    

    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    <!-- 雪花特效 -->
    

</body>

</html>